﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Collections.Specialized;
using AlipaySDK.Dto.Payment;
using AlipaySDK.Helper;

namespace User.Api.Helpers
{
    public class AlipayNotifyHelper
    {
        /// <summary>
        /// 转换支付宝的请求为字典数据
        /// </summary>
        /// <returns></returns>
        public static Dictionary<string, string> GetAlipayRequstParams(string strbody)
        {
            System.Text.Encoding gbkEncoding = System.Text.Encoding.GetEncoding("GBK");
            string[] plist = strbody.Split('&');
            Dictionary<string, string> dict = new Dictionary<string, string>();
            foreach (var p in plist)
            {
                string[] klist = p.Split('=');
                if (klist[0] == "biz_content")
                    dict.Add(klist[0], HttpUtility.UrlDecode(klist[1], gbkEncoding));
                else
                {
                    dict.Add(klist[0], klist[1]);
                }
            }
            return dict;
        }

        /// <summary>
        /// 获取支付宝POST过来通知消息，并以“参数名=参数值”的形式组成数组
        /// </summary>
        /// <returns>request回来的信息组成的数组</returns>
        public static Dictionary<string, string> GetRequestPost()
        {
            int i = 0;
            Dictionary<string, string> sArray = new Dictionary<string, string>();
            NameValueCollection coll;
            //Load Form variables into NameValueCollection variable.
            coll = HttpContext.Current.Request.Form;

            // Get names of all forms into a string array.
            String[] requestItem = coll.AllKeys;

            for (i = 0; i < requestItem.Length; i++)
            {

                sArray.Add(requestItem[i], HttpContext.Current.Request[requestItem[i]]);
            }

            return sArray;
        }

        /// <summary>
        /// 当面付退款
        /// </summary>
        /// <param name="trade_no">支付宝交易单号</param>
        /// <param name="outTradeNo">本地单号</param>
        /// <param name="total_fee">退款金额</param>
        /// <param name="openId">支付宝openId</param>
        public static AcquireRefundResponse AcquireRefund(string trade_no, string outTradeNo, decimal total_fee, string openId)
        {
            //找不到本地单号则直接退款给客户,防止在服务窗缴费时因二维码新请求造成订单单号变化
            PrecreatePayment payment = new PrecreatePayment();
            AcquireRefundResponse wapPayRefundResponse = payment.AcquireRefund(new AcquireRefundRequest
            {
                TradeNo = trade_no,
                BatchNo = DateTime.Now.ToString("yyyyMMddhhmmss") + DateTime.Now.Millisecond,
                RefundAmount = total_fee,
                RefundReason = "因找不到本地单而退款",
                OutTradeNo = outTradeNo
            });
            if (wapPayRefundResponse.ResultCode == "0" && wapPayRefundResponse.IsSuccess == "T")
            {
                //因用户扫码支付未关注服务窗，不用发消息通知
                if (!string.IsNullOrEmpty(openId))
                {
                    //退款成功，对于有支付宝支付交易号的订单发起发货失败已退款的通知
                    //var content = "由于找不到本地单号，您申请的 缴费(订单号：" +
                    //              outTradeNo + ") 交易失败，您缴纳的款项已退到您的支付账户中，请注意查收";
                    //CustomSend.SendTextMsg(openId, content);
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(openId))
                {
                    //退款失败，对于有支付宝支付交易号的订单发起发货失败退款中的通知
                    //var content = outTradeNo + "退款交易失败，订单关闭(超时)退款中";
                    //CustomSend.SendTextMsg(openId, content);
                }
            }
            return wapPayRefundResponse;

        }
    }
}